<template>
  <div class="auto">

    <!-- <button type="button" class="btn btn-default" @click="this.$goto('track-state', {}, 'master-router')">&lt;&lt;</button> -->
    &nbsp;<img src="../../../static/singleleft2.png" width="25" height="25" @click="this.$goto('track-state', {}, 'master-router')"></img>
    <center><label>{{f_user_name}}足迹</label></center>
    <div>
      <label>开始时间：</label>
      <input type="datetime-local" v-model="f_datetime_from"></input>
    </div>
    <div>
      <label>结束时间：</label>
      <input type="datetime-local" v-model="f_datetime_to"></input>&nbsp;&nbsp;&nbsp;
      <button type="button" class="btn btn-success" @click="refresh">刷新</button>
    </div>
    <div id="allmap" :style="mapStyle"></div>
  </div>
</template>

<script>
import * as Util from '../Util'
import co from 'co'
import Vue from 'vue'
// because of some weired behavior of baidu map, logic cant be extracted out and factored into a map component
let fetchPrints = function * (self) {
    let result = yield self.$post(Vue.url + 'sql/获取足迹?pageNo=1&pageSize=9999', {
        data: {
            f_user_id: self.f_user_id,
            startDate: self.f_datetime_from.replace('T', ' '),
            endDate: self.f_datetime_to.replace('T', ' ')
        }
    }, {
        resolveMsg: null,
        rejectMsg: '提取地图信息出错'
    })
    self.$set('markers', result.data)
    self.render()
}

export default {
  title: '足迹图',
  props: ['f_user_id', 'f_user_name'],
  data () {
    return {
      markers : [],
      f_datetime_from: Util.format3339TimeString(new Date(Date.now() - 24 * 3600 * 1000)),
      f_datetime_to: Util.to3339TimeString(),
      mapStyle: {
        width: this.$root.$el.clientWidth + 'px',
        height: (this.$root.$el.clientHeight - 177) + 'px'
      }
    }
  },
  ready () {
    if(Vue.mapLoaded) {
      window.map = new BMap.Map("allmap")
      this.refresh()
    } else {
      window.__mapCallback__ = this.mapCallback
      let element = document.createElement('script')
      element.setAttribute("type","text/javascript")
      element.setAttribute("src", 'http://api.map.baidu.com/api?v=2.0&ak=CAErfbr2DatVA6rHdoUELPynrdPh9A6S&callback=__mapCallback__')
      document.body.appendChild(element)
    }
  },
  methods: {
    verify () {
      let interval = Util.parse3339String(this.f_datetime_to).getTime() - Util.parse3339String(this.f_datetime_from).getTime()
      if (interval > 24 * 3600 * 1000) {
        HostApp.alert('时间段不能超过24小时，否则地图渲染过慢!')
        return false
      } else if (interval < 0){
        HostApp.alert('结束时间不能小于开始时间！')
        return false
      } else {
        return true
      }
    },
    refresh () {
      if(!this.verify())
        return
      let gen = fetchPrints(this)
      co(gen)
    },
    mapCallback () {
      window.map = new BMap.Map("allmap")
      Vue.mapLoaded = true
      this.refresh()
    },
    patch () {
      let a = document.getElementById('allmap').getElementsByClassName('BMap_cpyCtrl BMap_noprint anchorBL')
      if(a.length != 0) {
        a[0].style.height = 'auto'
      } else {
        window.setTimeout(this.patch, 500)
      }
    },
    render () {
      window.map.clearOverlays();
      if(this.markers.length == 0)
        window.map.centerAndZoom(new BMap.Point(116.404, 39.915), 11)
      else
        window.map.centerAndZoom(new BMap.Point(this.markers[0].longitude, this.markers[0].latitude), 11)
      window.map.addControl(new BMap.NavigationControl())
      let points = []
      this.markers.forEach(function(pos) {
        var point = new BMap.Point(pos.longitude,pos.latitude);
        points.push(point)
      	var marker = new BMap.Marker(point);  // 创建标注
      	window.map.addOverlay(marker);              // 将标注添加到地图中
      	var infoWindow = new BMap.InfoWindow(pos.hint);  // 创建信息窗口对象
      	marker.addEventListener("click", function(){
      		window.map.openInfoWindow(infoWindow,point); //开启信息窗口
      	});
      })
      var polyline=new BMap.Polyline(points, {strokeColor:"blue",strokeWeight:6,strokeOpacity:0.5})
      window.map.addOverlay(polyline);              // 将标注添加到地图中
      this.patch()
    }
  }
}
</script>
